package per.sunmes.lesrb.actor;

import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.ParticleEmitter;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.utils.Align;

public class ParticleActor extends Actor {

	ParticleEmitter pe;
	float offX, offY;
	float oldDuration;
	boolean oldContinuous;
	boolean isStoped;
	boolean isAutoRemove;

	public ParticleActor(ParticleEmitter pe) {
		this.pe = pe;
		setSize(12, 12);
	}

	public boolean isAutoRemove() {
		return isAutoRemove;
	}

	public void setAutoRemove(boolean isAutoRemove) {
		this.isAutoRemove = isAutoRemove;
	}

	public void start() {
		pe.start();
	}

	public void reset() {
		pe.duration = oldDuration;
		pe.setContinuous(oldContinuous);
		pe.reset();
		isStoped = false;
	}

	public void stop(float t) {
		oldContinuous = pe.isContinuous();
		pe.setContinuous(false);
		oldDuration = pe.duration;
		pe.duration = t;
		pe.durationTimer = 0;
		isStoped = true;
	}

	public boolean isStoped() {
		return isStoped;
	}

	public ParticleEmitter getParticleEffect() {
		return pe;
	}

	@Override
	public void act(float delta) {
		super.act(delta);
		pe.setPosition(getX(), getY());
		pe.update(delta);
		if (pe.isComplete()) {
			if (isAutoRemove) {
				remove();
			}
		}
	}

	@Override
	public void draw(Batch batch, float parentAlpha) {
		pe.draw(batch);
	}

	public void followActor(final Actor g) {
		clearActions();
		addAction(Actions.sequence(new Action() {
			@Override
			public boolean act(float delta) {
				if (g.getParent() == getParent()) {
					setPosition(g.getX() + g.getWidth() * g.getScaleX() / 2,
							g.getY() + g.getHeight() * g.getScaleY() / 2, Align.center);
				} else {
					pe.duration = 1;
					pe.durationTimer = 0;
					return true;
				}
				return false;
			}
		}, Actions.delay(1), Actions.removeActor()));
	}

	public float getOffX() {
		return offX;
	}

	public void setOffX(float offX) {
		this.offX = offX;
	}

	public float getOffY() {
		return offY;
	}

	public void setOffY(float offY) {
		this.offY = offY;
	}

	public void setOff(float ox, float oy) {
		offX = ox;
		offY = oy;
	}

}
